#include "comm.h"

int main()
{
    int shmid;// 创建共享内存块
    char *shmaddr ;
    struct shmid_ds buf ;	
    int i=0,index = 0,flag = 0 ;
    int pid ;	
	
	shmid = shmget(IPC_PRIVATE,4096,IPC_CREAT|IPC_EXCL|0666);
    if(shmid < 0){
        perror("get shm ipc_id error") ;
        return -2;
    }	

    pid = fork() ;

    if ( pid == 0 )
    {
		#if 1
		shmaddr  = shmat(shmid,NULL, 0 );
        if ( (int)shmaddr == -1 )
        {
            perror("shmat addr error") ;
            return -1 ;
        }
		#endif
		while( index < 4096)
		{
			#if 0
			shmaddr  = shmat(shmid,NULL, 0 );
			if ( (int)shmaddr == -1 )
			{
				perror("shmat addr error") ;
				return -1 ;
			}
			#endif
			printf("share memory@0x%x: %s\n", shmaddr , shmaddr );
			sleep(1);
			index++;
			if( index == 26)
				break; // 让程序结束
		}
		return 0;		
	} else if ( pid > 0) {

        flag = shmctl( shmid, IPC_STAT, &buf) ;

        if ( flag == -1 )
        {
            perror("shmctl shm error") ;
            return -1 ;
        }
        printf("shm_segsz =%d bytes\n", buf.shm_segsz ) ;

        printf("parent pid=%d, shm_cpid = %d \n", (int)getpid(), buf.shm_cpid ) ;

        printf("chlid pid=%d, shm_lpid = %d \n",pid , buf.shm_lpid ) ;

        shmaddr = (char *) shmat(shmid, NULL, 0 ) ;

        if ( (int)shmaddr == -1 )
        {
            perror("shmat addr error") ;
            return -1 ;
        }
		
		while( i < 4096)
		{
			shmaddr[i] = 'A'+i ;
			i++;
			sleep(1); 
			if(i == 26)
				break; // 让程序结束，去释放该共享内存
		}
			destroy_shm(shmid);	
	}else{
        perror("fork error") ;
        destroy_shm(shmid);
    }	
	return 0;
}
